<template>
  <el-dialog :visible.sync="isConfirmPop" @close="onClose" title="打印设置" @open="onOpen" custom-class="printSetting">
    <!-- <el-select v-for="item in keyArr" :key="item.id" v-model="selected[item.key]" multiple :placeholder="`请选择${nameArr[item.id - 1]}`" @change="onChange">
      <el-option v-for="item in headList[item.key]" :key="item.id" :label="item.name" :value="item.name"> </el-option>
    </el-select> -->
    <el-collapse v-if="isReady">
      <el-collapse-item v-for="item in keyArr" :key="item.id" :title="nameArr[item.id - 1]">
        <!-- <el-option v-for="item in headList[item.key]" :key="item.id" :label="item.name" :value="item.name"> </el-option> -->
        <span style="margin:5px 0;">已选择{{ selected[item.key] || 0 }}条</span>
        <div style="max-height:200px; overflow:auto;">
          <el-tree :ref="`tree${item.key}`" node-key="id" @check="onChange" :default-checked-keys="checked[item.key]" :data="headThList[item.key]" show-checkbox :props="{ label: 'name' }"> </el-tree>
        </div>
      </el-collapse-item>
    </el-collapse>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onClick" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { mapState } from "vuex";
export default {
  name: "printPop",
  props: {
    isPop: {
      type: Boolean,
      default: false
    },
    headList: {
      type: Object,
      default: () => {}
    },
    number: {
      type: String || Number,
      default: "all"
    },
    params: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    isPop(bol) {
      if (bol === true) {
        if (["all", "0", "1"].includes(this.number)) {
          this.confirmOpen();
        } else {
          // if (this.headList[this.keyArr[0].key].length <= this.maxNumber) {
          this.executePrint();
          this.onClose();
          // } else this.confirmOpen();
        }
      }
    }
  },
  computed: {
    ...mapState({
      companyList: state => state.reward.companyList,
      userInfo: state => state.common.userInfo
    }),
    keyArr() {
      console.log(this.headList);
      // this.headList[key].length > this.maxNumber
      return Object.keys(this.headList)
        .filter(key => this.number === "all" ? ["table1", "table2"].includes(key) : key === "table" + (Number(this.number) + 1))
        .map(key => ({ id: key.split("table")[1], key }));
    },
    headThList() {
      const obj = {};
      for (let key in this.headList) {
        const newArr = [];
        this.headList[key].forEach(item => {
          if (item.rowCode == 2) {
            const row = newArr.find(o => o.itemId == item.itemId);
            if (row) {
              if (!row?.children?.length) row.children = [];
              row.children.push({ ...item, key });
            }
          } else newArr.push({ ...item, children: [], key });
        });
        obj[key] = newArr;
      }
      return obj;
    }
  },
  data() {
    this.maxNumber = 20;
    this.nameArr = ["工资表", "考勤表", "社保公积金表", "专项附加扣除表"];
    return {
      isConfirmPop: false,
      checked: {},
      isReady: false,
      selected: {},
      loading: false
    };
  },
  methods: {
    setChecked() {
      this.isReady = false;
      for (let key in this.headList) {
        this.checked[key] = this.headList[key].filter(item => item.isPrint).map(item => item.id);
      }
      this.isReady = true;
    },
    confirmOpen() {
      this.isConfirmPop = true;
    },
    onOpen() {
      this.setChecked();
      this.selected = {};
    },
    onClose() {
      this.$emit("update:isPop", false);
      this.isConfirmPop = false;
    },
    onChange(o, obj) {
      const { key } = o;
      const { checkedNodes } = obj;
      const len = checkedNodes.filter(item => !item?.children?.length)?.length || 0;
      if (len > this.maxNumber) {
        this.$message({ message: `打印最多选择${this.maxNumber}项，请重新选择！`, type: "warning" });
        this.$refs?.["tree" + key][0]?.setChecked(o, false, true);
      } else this.$set(this.selected, key, len);
    },
    onClick() {
      console.log(this.selected);
      this.executePrint();
    },
    async executePrint() {
      try {
        this.loading = true;
        let arr = Array(4).fill(false);
        this.number === "all" ? arr.fill(true) : arr[this.number] = true;
        const [isSelectWage, isSelectAtt, isSelectSsaf, isSelectSad] = arr;

        const { subId, wagesId: id } = this.params;
        const subCompanyName = this.companyList?.find(item => item.subid == subId)?.subName;
        const params = {
          id: Number(id),
          subId,
          companyId: this.userInfo.CompanyId,
          subCompanyName,
          isSelectWage,
          isSelectSsaf,
          isSelectAtt,
          isSelectSad,
          headList: isSelectWage ? this.getSelectList(1) : [],
          attHeadList: isSelectAtt ? this.getSelectList(2) : []
          // ssafHeadList: this.getSelectList(3, true),
          // sadHeadList: this.getSelectList(4, true)
        };
        const { data, message } = await this.$api.smartSalary.wagesPrint(params).then(res => res.data);
        this.$message({ message, type: "success" });
        window.open(data);
        this.onClose();
      } finally {
        this.loading = false;
      }
    },
    getSelectList(n, bol) {
      const arr = new Set(this.$refs?.["treetable" + n]?.[0]?.getCheckedKeys() || []);
      return JSON.parse(JSON.stringify(this.headList))["table" + n].map(item => {
        return {
          ...item,
          isPrint: bol || arr.has(item.id)
        };
      });
    }
  }
};
</script>
<style lang="less">
.printSetting {
  .el-dialog__body {
    margin: 10px;
    .el-select {
      margin: 10px 0;
    }
    .el-collapse-item__header {
      font-size: 16px;
    }
    .el-collapse-item__content {
      font-size: 12px;
    }
  }
}
</style>
